<template>
  <!-- 产品栏目管理 -->
  <!-- 菜品分类 -->
  <div>
    <!-- 第一行开始 头部部分 -->
    <div class="header">
      <el-button type="primary" @click="toAddCategory">添加分类</el-button>
    </div>
    <!-- 第一行头部部分结束 -->
    <!-- 第二行开始 中间表单主体部分 -->
    <div class="center">
      <el-table :data="categoryData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" align="center" />
        <el-table-column
          prop="id"
          label="类别编号"
          width="180"
          align="center"
        />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="icon" label="图标" align="center">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="right">
              <img slot="reference" :src="scope.row.icon" alt="图片加载失败" />
              <img
                :src="scope.row.icon"
                alt="图片加载失败"
                style="width: 200px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tag type="success" class="ctrol" @click="toEdit(scope.row)"
              >编辑</el-tag
            >
            <el-tag type="danger" class="ctrol" @click="toDelete(scope.row.id)"
              >删除</el-tag
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 第二行结束 -->

    <!-- 模态框开始 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form ref="addForm" :model="form" :rules="rules">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="icon">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框结束 -->

    <el-pagination
      :current-page="params.page"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
// 引入上传图片的地址
import { uploadFileURL } from "@/utils/config";
import { pageQuery, addCategory, deleteCategory } from "@/api/proCategory";
export default {
  data() {
    return {
      categoryData: [],
      params: {
        page: 1,
        pageSize: 10,
      },
      visible: false,
      formLabelWidth: "120px",
      form: {},
      title: "",
      imageUrl: "",
      // 图片上传路径
      uploadFileURL,
      // 总条数
      total: 0,
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        icon: [{ required: true, message: "请选择封面", trigger: "change" }],
      },
    };
  },
  computed: {},
  created() {
    this.getCategoryData();
  },
  mounted() {},
  methods: {
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.icon = res.data;
    },

    // 图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 获取栏目分类信息
    async getCategoryData() {
      const res = await pageQuery(this.params);
      this.categoryData = res.data.list;
      this.total = res.data.total;
      // console.log(this.categoryData);
    },
    // 删除分类
    toDelete(id) {
      this.$confirm("次操作将永久删除该分类，是否继续操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteCategory({ id: id })
            .then((res) => {
              // 重新获取数据，刷新页面
              this.getCategoryData();
              this.$message({
                type: "success",
                message: res.message,
              });
            })
            .catch((err) => {
              this.$message.error({
                message: err.message,
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击添加按钮，开启模态框
    toAddCategory() {
      this.visible = true;
      this.title = "添加分类";
      // 清空表单
      this.form = {};
      // 清空imageUrl
      this.imageUrl = "";
    },
    // 编辑方法
    toEdit(row) {
      // 显示模态框
      this.visible = true;
      // 将标题改为编辑分类
      this.title = "编辑分类";
      // 将当前行的信息，给模态款的form表单设置
      this.form = row;
      // 让 imageUrl不为空，让图片显示出来
      this.imageUrl = "123";
    },
    // 模态框关闭
    toClose() {
      // console.log("123");
      // 清空表单
      this.$refs["addForm"].resetFields();
    },
    // 提交方法
    toSubmit() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const res = await addCategory(this.form);
          if (res.status === 200) {
            this.$message({
              message: "添加成功！",
              type: "success",
            });
            // 重新刷新页面
            this.getCategoryData();
          } else {
            this.$message.error({
              message: "添加失败",
            });
          }
          this.visible = false;
        } else {
          this.$message.error({
            message: "请正确输入数据",
          });
          return false;
        }
      });
    },
    // 页面条数发生改变
    handleSizeChange(size) {
      this.params.pageSize = size;
      // 重新请求数据
      this.getCategoryData();
    },
    // 当前页发生改变
    handleCurrentChange(page) {
      this.params.page = page;
      // 重新请求数据
      this.getCategoryData();
    },
  },
};
</script>
<style lang="scss" scoped>
.center {
  img {
    width: 30px;
    height: 30px;
  }
}
.center {
  .ctrol:hover {
    cursor: pointer;
  }
}
</style>
